﻿using ReflectionStudio.Core.Events;
using System;
using System.Data;
using System.Windows;
using System.Windows.Data;
using System.ComponentModel;
using WPFExcelReport.Helpers;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.OracleClient;
namespace WPFExcelReport
{
    public partial class TVA31XJ : UIVAKDBEZ
    {

        public TVA31XJ()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VVAKDBEZ();
            this.DataContext = MV;
            MESSAGES += "VAKDCHK;";
            InitializeComponent();
            VAR = "N";
            if (app.User.Trim() == "ITXV")
            {
                ART = "YB00";
            }
        }

        public override void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            if (IsLoaded)
                return;
            base.Window_Loaded(sender, e);
        }
        public override void vwMaster_CurrentChanged(object sender, EventArgs e)
        {
            base.vwMaster_CurrentChanged(sender, e);
            dwVAK = dwMaster;
            if (dwMaster == null)
            {
                KEY = "";
                TXTISIND = "";
                DES = "";
                KDFARBNR = "";
                KDKUNDNA = "";
                FARBGRP = "";
                CGRP = "";
            }
            else
            {
                KOLL = "XY   ";
                DES = dwVAK["VAFBEZ"].ToString();
                KDFARBNR = dwVAK["VAKBKDFARBNR"].ToString();
                KDKUNDNA = dwVAK["KDKUNDNA"].ToString();
                FARBGRP = dwVAK["VAFFARBGRP"].ToString();
                CGRP = dwVAK["CGRP"].ToString();
                CR = dwMaster["CR"].ToString();
                CG = dwMaster["CG"].ToString();
                CB = dwMaster["CB"].ToString();
                VAFBEZ = dwMaster["VAFBEZ"].ToString();
                TXTISIND = (dwMaster["VAKBKOLL"].ToString() + dwMaster["VAKBART"].ToString() + dwMaster["VAKBKUNDNR"].ToString().Trim().PadRight(8) + dwMaster["VAKBFARBE"].ToString()).PadRight(60);
                KEY = dwMaster["VAKBKOLL"].ToString().Trim().PadRight(5) + dwMaster["VAKBART"].ToString().Trim().PadRight(24) + dwMaster["VAKBFARBE"].ToString().Trim().PadRight(10) + dwMaster["VAKBKUNDNR"].ToString().Trim().PadRight(8);

            }
            CheckMat();
        }
        private SqlConnection _SQLDB;
        public SqlConnection SQLDB
        {
            get
            {
                if (_SQLDB == null)
                {
                    _SQLDB = new SqlConnection(app.SQLDB);
                }
                return _SQLDB;
            }
        }
        string UHEATHERHDRID = "";
        DataTable TBXJMAT = null;
        private void QueryXJCommand(object sender, RoutedEventArgs e)
        {

           // if (ART.Trim().Length < 2)
           // {
             //   MessageBox.Show("请提供两位前缀");
             //   ART = "YB";
            //    return;
           // }
            try
            {
                SqlCommand sql = SQLDB.CreateCommand();
                sql.CommandText = "SELECT 1 as ROWNID, A.SHEATHERCOLORNO AS VAKBFARBE,'N' AS ITXHAVE,'0' AS VAKBKUNDNR,UHEATHERHDRID, A.SHEATHERCOLORNO AS VAKBART,'Y'+A.SCOLORTYPE AS VAFFARBGRP,D.SDICTIONARYNAME AS VAFBEZ,  A.SHEATHERCOLORNAME AS VAFBEZ,B.SCUSTOMERSHORTNAME AS KDKUNDNA,A.SCUSTOMERCOLORNO AS VAKBKDFARBNR, A.SSEASON AS VAKBKOLL,A.SCOLORDEPTH AS CGRP,E.SDICTIONARYNAME,A.SCREATOR,A.DCREATETIME,A.SREMARK AS VAFBEZ,A.SOLDCOLORNO "
                    + ",'000' AS VAAGESANT1,'000' AS VAAGESANT2,'000' AS VAAGESANT3,'000' AS VAAGESANT4,'000' AS VAAGESANT5,'000' AS VAAGESANT6,'000' AS VAAGESANT7,'000' AS VAAGESANT8"
                + " FROM xjpdHeatherColorHdr  A LEFT JOIN xjsdCustomer B ON A.UCUSTOMERID = B.UCUSTOMERID"
                 + " LEFT JOIN XJSADICTIONARY  D ON A.SCOLORTYPE = D.SDICTIONARYVALUE AND D.SGROUPNAME ='颜色大类'"
                + " LEFT JOIN XJSADICTIONARY  E ON A.SCOLORDEPTH = E.SDICTIONARYVALUE AND E.SGROUPNAME ='颜色深度'"
                + " WHERE A.SHEATHERCOLORNO LIKE '" + ART.Trim() + "%' "
                 + " ORDER BY SHEATHERCOLORNO";
                SResult = INTEXDBC.Connect2Proxy(sql);
                SResult.Tables[0].TableName = TB;
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    foreach (DataColumn cm in SResult.Tables[0].Columns)
                    {
                        string koll = row["VAKBKOLL"].ToString().Trim();
                        if (koll.Length == 0)
                            koll = "XY   ";
                        row["VAKBKOLL"] = Helper.Left(koll.PadRight(5), 5);
                        row["VAKBART"] = Helper.Left(row["VAKBART"].ToString().PadRight(24), 24);
                        row["VAKBFARBE"] = Helper.Left(row["VAKBFARBE"].ToString().PadRight(10), 10);
                        row[cm.ColumnName] = Helper.ConvertGB2312To8859P1(row[cm.ColumnName].ToString());
                    }
                }
                MergeData(SResult, true, true);
                TBXJMAT = null;
                int idx = 1;
                foreach (DataRow row in TBMain.Rows)
                {
                    row["ROWNID"] = idx;
                    idx++;
                }
                CheckIntex();
                LOADMAT();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);

            }
        }
        DataTable TBKD
        {
            get
            {
                return cKD02.TBMain;

            }
        }

        public void CheckMat()
        {
            if (dwMaster == null)
                return;
            if (TBXJMAT == null)
                return;
            LFD = "0";
            if (UHEATHERHDRID.Length < 1)
            {
                TBMAT = null;
                return;
            }
            filter = "UHEATHERHDRID= '" + UHEATHERHDRID + "'";
            rows = TBXJMAT.Select(filter);
            TBMAT = rows.CopyToDataTable();
            LFD = TBMAT.Rows.Count.ToString();
        }
        public void LOADMAT()
        {
            SqlCommand sql = SQLDB.CreateCommand();
            sql.CommandText = "SELECT a.UHEATHERHDRID as UHEATHERHDRID,a.SHEATHERCOLORNO AS VAFFARBE,C.SFIBREELEMENT,C.SFIBREELEMENTVALUE AS GSMRFARBE, C.SFIBREELEMENTVALUE AS GSMRSPZ,  10*C.NPERCENT AS GSMRANT  FROM xjpdHeatherColorHdr a"
              + "  JOIN xjpdHeatherColorDtl C ON A.UHEATHERHDRID = C.UHEATHERHDRID";
            SResult = INTEXDBC.Connect2Proxy(sql);
            TBXJMAT = SResult.Tables[0].Copy();
            foreach (DataRow row in TBMain.Rows)
            {
                UHEATHERHDRID = row["UHEATHERHDRID"].ToString();
                sort = "GSMRANT ";
                filter = "UHEATHERHDRID= '" + UHEATHERHDRID + "'";
                rows = TBXJMAT.Select(filter);
                int idx = 1;
                foreach (DataRow dwGS04 in rows)
                {
                    row["VAAGESANT" + idx] = dwGS04["GSMRANT"].ToString();
                    row["VAAGESBEZ" + idx] = dwGS04["GSMRSPZ"].ToString();
                    idx++;
                }

            }
        }
        DataTable TBVAK = null;
        public void CheckIntex()
        {
            vwMaster.View.MoveCurrentTo(-1);
            dwData = TBMain.NewRow();
            dwData["VAKBMANDANT"] = app.Mandant;
            SResult = TMV.QVAK08(dwData);
            TBVAK = SResult.Tables[0].Copy();
            foreach (DataRow row in TBMain.Rows)
            {
                string color = row["VAKBFARBE"].ToString();
                filter = "VAKBFARBE='" + color + "'";
                rows = TBVAK.Select(filter);
                if (rows.Length > 0)
                {
                    row["ITXHAVE"] = "J";
                }
            }
        }

        private void ExcelCommand(object sender, RoutedEventArgs e)
        {
            try
            {
                DataSet Set = new DataSet();
                foreach (DataRow row in TBMain.Rows)
                {
                    row["ITXHAVE"] = "N";//导出标志所有未导入
                    for (int idx = 1; idx < 9; idx++)
                    {
                        row["VAAGESANT" + idx] = 0.1 * Convert.ToDouble(row["VAAGESANT" + idx].ToString());
                    }

                }
                //Set.Merge(TBMain,false,MissingSchemaAction.Ignore);
                cDR.PRINT(TMV.SetProd);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        /// <summary>
        /// 成分，客户名称一致
        /// 比例扩大10倍
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadExtCommand(object sender, RoutedEventArgs e)
        {

            try
            {
                DataSet Set = new DataSet();
                cDREXT.PRINT(Set);
                SResult = cDREXT.SetExchange;
                MergeData(SResult, false, true);
                foreach (DataRow rx in TBMain.Rows)
                {
                    //rx["KDKUNDNA"] = Helper.ConvertGB2312To8859P1(rx["KDKUNDNA"].ToString().Trim()).PadRight(8);
                    rx["KDKUNDNA"] =  rx["KDKUNDNA"].ToString().Trim().PadRight(8);
                    rx["VAFBEZ"] = Helper.ConvertGB2312To8859P1(rx["VAFBEZ"].ToString().Trim()).PadRight(20);
                    rx["VAKBKOLL"] = Helper.ConvertGB2312To8859P1(rx["VAKBKOLL"].ToString().Trim()).PadRight(5);
                    rx["VAKBART"] = Helper.Left(rx["VAKBFARBE"].ToString().PadRight(24), 24);
                    rx["VAKBKDFARBNR"] = Helper.ConvertGB2312To8859P1(rx["VAKBKDFARBNR"].ToString().Trim()).PadRight(29);
                    rx["VAKBKDARTBEZ"] = Helper.ConvertGB2312To8859P1(rx["VAKBKDARTBEZ"].ToString().Trim()).PadRight(29);
                    filter = "KDKUNDNA='" + rx["KDKUNDNA"].ToString().Trim().PadRight(8) + "'";
                    rows = TBKD.Select(filter);
                    if (rows.Length == 0)
                        throw new Exception(rx["VAKBFARBE"].ToString() + "," + rx["KDKUNDNA"] .ToString()+ ":客户不存在，终止");
                    rx["VAKBKUNDNR"] = rows[0]["KDKUNDNR"];
                    for (int idx = 1; idx < 9; idx++)
                    {
                        rx["VAAGESANT" + idx] = 10 * Convert.ToDouble(rx["VAAGESANT" + idx].ToString());
                    }
                }
                filter = "ITXHAVE='J'";//这里控制
                rows = TBMain.Select(filter);
                foreach (DataRow row in rows)
                {
                    //row.Delete();//不再检查是否已经有色号存在。因为前面的判断条件不完善，未检查品种名称和客户。若是前面判断 ITXHAVE具有了完备机制，则可以启用
                }
                CheckIntex();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void Auto2ITXCommand(object sender, RoutedEventArgs e)
        {
            EventDispatcher.Instance.RaiseStatus("导入intex开始", StatusEventType.StartProgress);
            int id = 0;
            try
            {
                foreach (DataRow row in TBMain.Rows)
                {
                    id++;
                    dwData = TBMain.NewRow();
                    TMV.SetUpNewRow(ref dwData, null);
                    dwData["VAKBKOLL"] = Helper.Left(row["VAKBKOLL"].ToString().PadRight(5), 5);
                    dwData["VAKBART"] = Helper.Left(row["VAKBFARBE"].ToString().PadRight(24), 24);
                    dwData["VAKBKUNDNR"] = Helper.Right("00000000" + row["VAKBKUNDNR"].ToString().PadRight(8), 8);
                    dwData["VAKBFARBE"] = Helper.Left(row["VAKBFARBE"].ToString().PadRight(10), 10);
                    dwData["VAKBKDFARBNR"] = Helper.Left(row["VAKBKDFARBNR"].ToString().PadRight(29), 29);
                    dwData["VAKBKDARTBEZ"] = Helper.Left(row["VAKBKDARTBEZ"].ToString().PadRight(29), 29);
                    TMV.DeleteVAKDBEZ(dwData, 1);
                    TMV.BATCHWB14(dwData);
                    EventDispatcher.Instance.RaiseStatus(id + "@" + Counts, StatusEventType.RunningProgress);
                }
                TMV.POSTCHG();

                vwMaster.View.MoveCurrentTo(-1);
                cGS04.IsAuto = true;
                cVA30.IsAuto = true;
                for (int idx = 0; idx < Counts; idx++)
                {
                    vwMaster.View.MoveCurrentToNext();
                }
                cGS04.IsAuto = false;
                cVA30.IsAuto = false;
                EventDispatcher.Instance.RaiseStatus("导入完成", StatusEventType.StopProgress);
                MessageBox.Show("导入完成");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}
